﻿using System;
using System.DirectoryServices;
using System.Globalization;
using Ihc.Common;
using Ihc.Wcp.Portal.Admin.Controls;
using Ihc.Wcp.Portal.Domain.Models.Users;
using Ihc.Wcp.Portal.Domain.Services;
using Ihc.Wcp.Security.ActiveDirectory;
using Ihc.Wcp.Security.Web;

namespace Ihc.Wcp.Portal.UserControls.DocumentControls.Xslt
{
    public class XslExtentions
    {
        public string GetCurrentDate()
        {
            return DateTime.Now.ToString("dd-MMM-yyyy");
        }

        public string GetCurrentTime()
        {
            return DateTime.Now.ToString("HH:mm");
        }

        public string GetCurrentUserFullName()
        {
            return getUsername(UserSession.CurrentSession.IdentityName);
        }

        public string GetUserFullName(string username)
        {
            return getUsername(username);
        }

        public string TitleCase(string text)
        {
            if (string.IsNullOrEmpty(text))
                return text;

            var ti = new CultureInfo("en-US", false).TextInfo;
            return ti.ToTitleCase(ti.ToLower(text));
        }

        public string UpperCase(string text)
        {
            if (string.IsNullOrEmpty(text))
                return text;

            var ti = CultureInfo.CurrentUICulture.TextInfo;
            return ti.ToUpper(text);
        }

        public string FormatBool(string input, string trueValue, string falseFalse)
        {
            bool value;
            if (string.IsNullOrEmpty(input) || !bool.TryParse(input, out value))
                return input;

            return value ? trueValue : falseFalse;
        }
       
        public string getUsername(string login)
        {
            if (string.IsNullOrEmpty(login))
                return string.Empty;
            
            var service = new ActiveDirectoryService<ActiveDirectoryUser>();
            ActiveDirectoryUser user = null;
            try
            {
                user = service.FindUserByLogin(login);
            }
            catch {
                return login;
            }

            return string.Format("{0} {1}", user.FirstName, user.LastName); 
        } 
    }
}